<script setup>
import { ref, computed, onMounted, watch, reactive } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const rulesa = ref(null);
// 添加自定义表单验证规则
const rules = reactive({
  in_id:[{ required: true, message: '请输入入库单号', trigger: 'blur' }],
  in_name:[{ required: true, message: '请输入供应商名', trigger: 'blur' }],
  in_sums_price:[{ required: true, message: '请添加商品', trigger: 'blur' }],
  in_date:[{ required: true, message: '请输入入库日期', trigger: 'blur' }],
  user_name:[{ required: true, message: '请输入操作人员姓名', trigger: 'blur' }],
  // 验证入库数量大于0
  'order.list.in_num': [{ 
    validator: (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error('入库数量必须为大于0的正整数'));
      } else {
        callback();
      }
    }, trigger: 'blur'
  }]
});
// 数据
const viewWinVisible = ref(false);
const selectedRows = ref([]);
const allData = ref([]);
const tableData = ref([]);
const searchQuery = ref('');
const order = ref({
  in_id: '',
  in_name: '',
  in_date: '',
  user_name: '',
  in_sums_price: 0,
  list: []
});

// 计算属性
const formattedInDate = computed(() => {
  return order.value.in_date ? new Date(order.value.in_date).toLocaleString() : '';
});

// 方法
const fetchAllInventory = async () => {
  try {
    const response = await axios.get('/api/inventory/all');
    allData.value = response.data.data;
    total.value = allData.value.length;
    paginate();
  } catch (error) {
    ElMessage.error('获取失败: ' + (error.response?.data?.message || '未知错误'));
  }
};

const searchInventory = () => {
  const query = searchQuery.value.toLowerCase();
  const filteredData = allData.value.filter(item =>
    item.product_name.toLowerCase().includes(query) ||
    item.product_id.toLowerCase().includes(query)
  );
  total.value = filteredData.length;
  paginate();
};

const viewAndAddItems = () => {
  fetchAllInventory();  // 加载商品列表
  viewWinVisible.value = true;  // 打开弹窗
};


const removeItem = (index) => {
  order.value.list.splice(index, 1);
  updateTotalPrice();
};

// 方法
const validateAndCalculate = (row, field) => {
  if (field === 'in_num') {
    if (row.in_num <= 0) {
      ElMessage.error('入库数量必须大于0');
      row.in_num = 1; // 如果数量小于等于0，则重置为1
    }

    row.in_sum_price = row.in_num * row.in_price;
  }
  updateTotalPrice();
};


const updateTotalPrice = () => {
  order.value.in_sums_price = order.value.list.reduce((sum, item) => sum + item.in_sum_price, 0);
};

const submitOrder = async () => {
  rulesa.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保日期时间格式正确
        const orderToSubmit = {
          ...order.value,
          in_date: formatDate(new Date())
        };
        // 提交表单数据
        await axios.post('/api/order/inadds', orderToSubmit);
        ElMessage.success('提交成功');
        window.location.reload();
      } catch (error) {
        ElMessage.error('提交失败: ' + (error.response?.data?.message || '未知错误'));
      }
    } else {
      ElMessage.error('请检查表单填写是否正确');
    }
  });
};

const resetForm = () => {
  order.value = {
    in_id: '',
    in_name: '',
    in_date: '',
    user_name: '',
    in_sums_price: 0,
    list: []
  };
  generateOrderId(); // 重置表单时生成新的入库单号
  setRealTimeDate(); // 重置表单时重新获取当前时间
};


// 组件加载时生成入库单号
const generateOrderId = () => {
  const now = new Date();
  // 提取年份
  const year = now.getFullYear();
  // 提取月份和日期，确保是两位数
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  // 生成一个随机的6位数字
  const randomNum = Math.floor(100000 + Math.random() * 1000000); // 确保是6位数
  // 组合年份，日期和随机数
  order.value.in_id = `IN${year}${month}${day}${randomNum}`;
};


// 更新时间
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
};

const setRealTimeDate = () => {
  order.value.in_date = formatDate(new Date());
  setInterval(() => {
    order.value.in_date = formatDate(new Date());
  }, 1000);
};

// 确认添加选中的商品
const addSelectedItems = () => {
  
  selectedRows.value.forEach(item => {
    const existingItem = order.value.list.find(row => row.product_id === item.product_id);
    if (!existingItem) {
      order.value.list.push({
        product_id: item.product_id,
        product_name: item.product_name,
        stock_num: item.number, // 初始化库存数量
        in_num: 1, // 默认入库数量为0
        util: item.util,
        in_price: item.in_price,
        in_sum_price: item.in_price,
      });
    }
  });
  updateTotalPrice();
  closeViewWin();
};

// 关闭查看商品窗口
const closeViewWin = () => {
  viewWinVisible.value = false;
};

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 分页状态
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示的数量
const total = ref(0); // 数据总数

// 计算当前页数据
const paginate = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  tableData.value = allData.value.slice(start, end);
};

// 处理分页变化
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  paginate();
};

// 初始化数据
onMounted(() => {
  generateOrderId();
  fetchAllInventory();
  setRealTimeDate(); // 调用函数以设置实时日期
});

// Watcher for search query changes
watch(searchQuery, () => {
  searchInventory();
});
</script>


<template>
  <div class="goods-in">
    <el-card>
      <h2>商品入库</h2>
      <el-form :model="order" label-width="120px" @submit.native.prevent="submitOrder" :rules="rules" ref="rulesa">
        <!-- 入库单号输入框 -->
        <el-form-item label="入库单号:" prop="in_id" >
          <el-input v-model="order.in_id" placeholder="自动生成" :readonly="true"></el-input>
        </el-form-item>
        <!-- 供应商名输入框 -->
        <el-form-item label="供应商名:" prop="in_name" >
          <el-input v-model="order.in_name" placeholder="输入供应商名"></el-input>
        </el-form-item>
        <!-- 总价格显示 -->
        <el-form-item label="总价格:" prop="in_sums_price" >
          <el-input v-model="order.in_sums_price" :readonly="true"></el-input>
        </el-form-item>
        <!-- 日期输入框 -->
        <el-form-item label="出库日期:" prop="in_date" >
          <el-input v-model="order.in_date" :readonly="true"></el-input>
        </el-form-item>
        <!-- 操作人员输入框 -->
        <el-form-item label="操作人员:" prop="user_name" >
          <el-input v-model="order.user_name" placeholder="输入操作人员姓名"></el-input>
        </el-form-item>
        <!-- 商品列表 -->
        <el-form-item label="商品列表" prop = "inventoryList" >
          <el-table :data="order.list">
            <el-table-column prop="product_id" label="商品编码">
              <template v-slot="scope">
                <el-input v-model="scope.row.product_id" :readonly="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="product_name" label="商品名称">
              <template v-slot="scope">
                <el-input v-model="scope.row.product_name" :readonly="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="stock_num" label="库存数量">
              <template v-slot="scope">
                <el-input v-model="scope.row.stock_num" :readonly="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="order.list.in_num" label="入库数量" >
              <template v-slot="scope">
                <el-input type="number" v-model.number="scope.row.in_num" :min="0" @input="validateAndCalculate(scope.row, 'in_num')" placeholder="输入入库数量"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="util" label="单位">
              <template v-slot="scope">
                <el-input v-model="scope.row.util" :readonly="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="in_price" label="入库单价">
              <template v-slot="scope">
                <el-input type="number" v-model.number="scope.row.in_price" :readonly="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="in_sum_price" label="单品总价">
              <template v-slot="scope">
                <el-input type="number" v-model.number="scope.row.in_sum_price" :readonly="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button @click="removeItem(scope.$index)" type="danger" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="success" @click="viewAndAddItems">添加商品</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitOrder">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog v-model="viewWinVisible" title="查看所有商品" width="800">
      <el-input v-model="searchQuery" placeholder="搜索商品" @input="searchInventory" style="margin-bottom: 10px;"></el-input>
      <el-table :data="tableData" @selection-change="handleSelectionChange">
        <!-- 选择框列 -->
        <el-table-column type="selection" label="选择" width="55"></el-table-column>
        
        <el-table-column prop="product_id" label="商品编码"></el-table-column>
        <el-table-column prop="product_name" label="商品名称"></el-table-column>
        <el-table-column prop="location" label="商品位置"></el-table-column>
        <el-table-column prop="number" label="商品数量"></el-table-column>
        <el-table-column prop="util" label="单位"></el-table-column>
        <el-table-column prop="in_price" label="入库价格"></el-table-column>
        <el-table-column prop="out_price" label="出库价格"></el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button  type="primary" @click="addSelectedItems">确认添加</el-button>
          <el-button @click="closeViewWin">关闭</el-button>
        </div>
      </template>
      <!-- start 分页组件 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handlePageChange">
      </el-pagination>
      <!-- end 分页组件 -->
    </el-dialog>
  </div>
</template>

<style scoped>
/* 设置对话框背景透明 */
.el-dialog__wrapper {
  background-color: rgba(252, 6, 6, 0.5); /* 半透明背景 */
}

/* 设置对话框内容区域背景颜色 */
.el-dialog {
  background-color: #ffffff; /* 对话框背景颜色，保持不透明 */
}

/* 可选：设置标题区域背景颜色 */
.el-dialog__header {
  background-color: #ffffff; /* 标题区域背景颜色 */
}

/* 可选：设置内容区域背景颜色 */
.el-dialog__body {
  background-color: #ffffff; /* 内容区域背景颜色 */
}

/* 可选：设置底部区域背景颜色 */
.el-dialog__footer {
  background-color: #ffffff; /* 底部区域背景颜色 */
}
</style>